package com.olympia.myapp.activity;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.xml.sax.InputSource;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.olympia.myapp.R;
import com.olympia.myapp.base.BaseActivity;
import com.olympia.myapp.custom.Dialog_Confirm;
import com.olympia.myapp.custom.Dialog_Confirm.ProcessDialogConfirm;
import com.olympia.myapp.custom.Dialog_Login;
import com.olympia.myapp.custom.Dialog_Login.ProcessDialogLogin;
import com.olympia.myapp.custom.Dialog_Regis;
import com.olympia.myapp.custom.Dialog_Regis.ProcessDialogRegis;
import com.olympia.myapp.entity.Player;
import com.olympia.myapp.server.HttpConnection;
import com.olympia.myapp.server.URLServer;
import com.olympia.myapp.sound.MyService;
import com.olympia.myapp.util.Constants;
import com.olympia.myapp.util.Settings;
import com.olympia.myapp.xml.MyXMLParser;

public class SplashActivity extends BaseActivity {
	ProgressBar progress = null;
	RelativeLayout layoutButton = null;
	Dialog_Confirm dgConfirm = null;
	static int typeConnect = 0;// 0 getserver, 1 login, 2 đang ký

	private ServiceConnection mConection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			Constants.myService = ((MyService.LocalBinder) service).getLocal();
		}

		public void onServiceDisconnected(ComponentName name) {
			Constants.myService = null;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);

		// admdob
		// AdView adView = (AdView) this.findViewById(R.id.adView);
		// adView.bringToFront();
		// AdRequest rq = new AdRequest();
		// rq.setTesting(true);
		// adView.loadAd(rq);

		progress = (ProgressBar) findViewById(R.id.progress);
		layoutButton = (RelativeLayout) findViewById(R.id.splash_layout_button);

		ServiceConnection conn = mConection;
		if (conn != null && !isFinishing()) {
			bindService(new Intent(this, MyService.class), conn,
					Context.BIND_AUTO_CREATE);
		}
		// request để kiểm tra server có kết nối được không
		String urlConnect = urlUtil.connectServer();
		typeConnect = 0;
		requestServer(urlConnect);
	}

	@Override
	protected void onResume() {
		String[] str = Settings.getpPlayer(this);
		if (str != null && str[0].length() > 0) {
			((Button) findViewById(R.id.splash_btnRegis))
					.setVisibility(View.GONE);
		}
		super.onResume();
	}

	/**
	 * ẩn hiện progressbar
	 * 
	 * @param isShow
	 */
	private void showhideProgress(boolean isShow) {
		isRequest = isShow;
		progress.setVisibility(isShow ? View.VISIBLE : View.GONE);
	}

	/*
	 * hien thi dialog confirm
	 */
	private void showDialogConfirm(String title, String content) {
		if (dgConfirm == null) {
			dgConfirm = new Dialog_Confirm(SplashActivity.this, title, content,
					true, true, new ProcessDialogConfirm() {
						public void click_Ok() {
							typeConnect = 0;
							String urlConnect = urlUtil.connectServer();
							requestServer(urlConnect);
						}

						public void click_Cancel() {
							Constants.myService.clearAll();
							Constants.myService = null;
							finish();
						}
					});
		}

		dgConfirm.setContent(content);
		dgConfirm.show();
	}

	/**
	 * ======================= Kết nối đến server =========================
	 */
	public void requestServer(String url) {
		if (!isRequest) {
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message message) {
					switch (message.what) {
					case HttpConnection.DID_START: {
						showhideProgress(true);
						break;
					}
					case HttpConnection.DID_SUCCEED: {
						String result = message.obj.toString();
						try {
							processDataResult(result, typeConnect);
						} catch (IOException e) {
							e.printStackTrace();
						}
						showhideProgress(false);
						break;
					}
					case HttpConnection.DID_ERROR: {
						showhideProgress(false);
						if (typeConnect == 0) {
							showDialogConfirm("Thông báo",
									"Không thể kết nối đến máy chủ, Xin vui lòng kết nối lại");
						} else {
							msgUtil.showToast(context,
									"Không thể kết nối đến máy chủ.");
						}
						break;
					}
					}
				}
			};

			new HttpConnection(handler).get(url, typeConnect);
		}
	}

	private void processDataResult(String str, int index) throws IOException {
		if (str != null && str.length() > 0) {
			switch (index) {
			case 0:
				URLServer.URLSERVER = str;
				// hiển thị các nút login, đang ký và tham gia
				layoutButton.setVisibility(View.VISIBLE);
				Constants.myService.playBegin();
				break;
			case 1:
				if (dgLogin != null)
					dgLogin.progress.setVisibility(View.GONE);
				URL sourceUrl = new URL(urlLogin);
				List<String> content = MyXMLParser
						.parseLoginData(new InputSource(sourceUrl.openStream()));
				if (content != null && content.size() > 0) {
					if (content.get(0).toString().toUpperCase().equals("OK")) {
						Constants.myAccount = new Player(1000, content.get(1),
								emailRegis, content.get(2), content.get(3),
								content.get(4), content.get(5), content.get(6));
						// dừng âm thanh ở màn hình này
						Constants.myService.pauseBegin();
						// chuyển sang form player list
						intent = new Intent(SplashActivity.this,
								PlayerListActivity.class);
						intent.putExtra("pass", passRegis);
						dgLogin.dismiss();
						startActivity(intent);
						overridePendingTransition(R.anim.fase_in,
								R.anim.fade_out);
					} else if (content.get(0).toString().toUpperCase()
							.equals("ERPASS")) {
						msgUtil.showToast(this,
								"Mật khẩu không đúng. Vui lòng kiểm tra lại");
					} else if (content.get(0).toString().toUpperCase()
							.equals("EREMAIL")) {
						msgUtil.showToast(this, "Địa chỉ mail không tồn tại");
					}
				} else {
					msgUtil.showToast(this, "Dữ liệu không hợp lệ");
				}
				break;
			case 2:
				if (dgRegis != null)
					dgRegis.progress.setVisibility(View.GONE);
				// đang ky thanh cong hay không
				if (str.contains("EREMAIL")) {
					msgUtil.showToast(this,
							"Email không đúng hoặc đã được đăng ký");
				} else {// tien hanh Login ngầm
					dgRegis.dismiss();
					msgUtil.showToast(this,
							"Bạn đã đăng ký thành công. Đăng nhập để tham gia chương trình");
					showDialogLogin(emailRegis, passRegis);
				}

				break;
			default:
				break;
			}
		} else {
			msgUtil.showToast(this, index == 1 ? "Đăng nhập không thành công"
					: "Đăng ký không thành công");
		}
	}

	/**
	 * ================= Handler Click on XML ============================
	 */
	public void clickHelp(View view) {
		intent = new Intent(SplashActivity.this, InfoActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.fase_in, R.anim.fade_out);
	}

	Dialog_Login dgLogin = null;
	Dialog_Regis dgRegis = null;
	String emailRegis = "";
	String passRegis = "";
	String urlLogin = "";

	public void clickRegis(View view) {
		dgRegis = new Dialog_Regis(SplashActivity.this,
				new ProcessDialogRegis() {
					public void click_Ok(String mail, String pass) {
						// tiến hanh đang ký
						typeConnect = 2;
						emailRegis = mail;
						passRegis = pass;
						String urlRegis = urlUtil.regis(Constants.VERSION, "",
								mail, pass);
						requestServer(urlRegis);
					}
				});
		if (!dgRegis.isShowing())
			dgRegis.show();
	}

	public void clickAdd(View view) {
		showDialogLogin("", "");
	}

	private void showDialogLogin(String email, String pass) {
		String[] layer = Settings.getpPlayer(this);

		dgLogin = new Dialog_Login(SplashActivity.this,
				new ProcessDialogLogin() {

					public void click_Ok(String mail, String pass) {
						// tiến hanh đang nhập
						typeConnect = 1;
						emailRegis = mail;
						passRegis = pass;
						urlLogin = urlUtil.login(Constants.VERSION, mail, pass);
						requestServer(urlLogin);

						Settings.savePlayer(context, mail, pass);
					}

					public void click_Regis() {
						dgRegis = new Dialog_Regis(SplashActivity.this,
								new ProcessDialogRegis() {
									public void click_Ok(String mail,
											String pass) {
										// tiến hanh đang ký
										typeConnect = 2;
										String urlRegis = urlUtil.regis(
												Constants.VERSION, "", mail,
												pass);
										requestServer(urlRegis);
									}
								});
						if (!dgRegis.isShowing())
							dgRegis.show();
					}
				});
		if (email.length() > 0 || pass.length() > 0) {
			dgLogin.setText(email, pass);
			dgLogin.hideBtnRegis();
		} else if (layer[0].toString().length() > 0
				|| layer[1].toString().length() > 0) {
			dgLogin.setText(layer[0].toString(), layer[1].toString());
			dgLogin.hideBtnRegis();
		}
		if (!dgLogin.isShowing())
			dgLogin.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		Constants.myService.clearAll();
		super.onBackPressed();
	}
}